<?php

namespace app\admin\controller;
use app\common\model\GroupAccess;

/**
 * 用户管理
 * Class Admin
 * @package app\admin\controller
 */
class Admin extends Common
{
    private  $db;
    public function __construct()
    {
        parent::__construct();
        $this->db = new \app\common\model\Admin();
    }

    public function index(){
        $userData = db('user')->select();
        $this->assign('userData',$userData);
        //载入模板
        return view();
    }
    public function add(){
        if(request()->isPost()){
            $res = $this->db->add(input('post.'));
            if($res){
                $this->error($res['msg']);
            }else{
                $this->success($res['msg'],'admin/admin/index');
            }
        }
        return view();
    }
    public function delete(){
        $uid = input('param.uid');
        $row = db('user')->delete($uid);
        if($row){
            $this->success('删除成功','admin/admin/index');
        }else{
            $this->error('删除失败');
        }
    }

    public function edit(){
        $uid = input('param.uid');
        $oldData = db('user')->where('uid',$uid)->select();
        $this->assign('oldData',$oldData[0]);
        if(request()->isPost()){
            $res = $this->db->edit($uid);
            if($res){
                $this->success('编辑成功','admin/admin/index');
            }else{
                $this->error($res['msg']);
            }
        }
        return view();
    }

    /**
     * 分配权限  在用户管理   规则管理   用户组管理后面添加的一个方法
     */
    public function setAuth(){
        //1.获取用户组数据
        $groupData = db('authgroup')->select();
        //2.获取当前用户名
        $uid = input('param.uid');
        $username = db('user')->where('uid',$uid)->value('username');
        //3.操作数据(第一次是执行添加)
        if(request()->isPost()){
            $res = (new GroupAccess())->setAuth(input('post.'));
            if ($res['valid']) {
                $this->success($res['msg'], 'admin/admin/index');
            } else {
                $this->error($res['msg']);
            }
        }
        //4.执行完第一次添加之后就是编辑操作  所以要获取旧数据
        $checkGroup = db('authgroupaccess')->where('uid',$uid)->column('group_id');
        //载入模板并分配变量
        return view('',compact(['groupData','username','checkGroup']));
    }
}
